#!/usr/bin/env bash

# export giteePullRequestIid=12
# export BUILD_DIR=/data/pr
# export giteeSourceBranch=docs-develop

set -e

conName="pr_"${giteePullRequestIid}
dir=${BUILD_DIR}/"pr_"${giteePullRequestIid}
cacheDir=${dir}/cache
publicDir=${dir}/publicDir
pr_port_file=${dir}/pr_port.txt

if [ ! -d ${cacheDir} ];then
  mkdir -p ${cacheDir}
fi

echo "giteePullRequestIid : ${giteePullRequestIid}"
echo "giteeTargetBranch   : ${giteeTargetBranch}"

# 删除文件
rm -rf .cache
rm -rf public
mkdir public

# 恢复文件
echo "Restore Cache as $(date '+%Y-%m-%d %H:%M:%S')"
if [ ! -d ${publicDir} ];then
    if [[ ${giteeTargetBranch} == "master" ]]; then
        rsync -rltgoD --delete /data/mogdb-docs/ public
    else
        echo "mogdb-beta-docs"
        rsync -rltgoD --delete /data/mogdb-beta-docs/ public
    fi
else
   rsync -rltgoD --delete ${publicDir}/ public
fi

mv ${cacheDir} .cache

node -v

echo "Dep install as $(date '+%Y-%m-%d %H:%M:%S')"
# npm install
yarn install
retCode=$?
if [[ ${retCode} != 0 ]]; then
    exit 1
fi

echo "Start Build as $(date '+%Y-%m-%d %H:%M:%S')"
yarn build --verbose
# npm run build
retCode=$?
if [[ ${retCode} != 0 ]]; then
    exit 1
fi

echo "Backup Cache as $(date '+%Y-%m-%d %H:%M:%S')"
# 备份文件
mv .cache ${cacheDir}
rsync -rltgoD --delete public/ ${publicDir}

if [ `docker ps -a |awk '{print $NF}' |grep "^${conName}$" | wc -l` -gt 0 ]; then
    docker rm -f ${conName}
fi

if [ -f ${pr_port_file} ];then
  pr_port=`cat ${pr_port_file}`
else
    for port in {9001..10000};
    do
        if [ `netstat -apn |grep ${port} | wc -l` -eq 0 ]; then
            pr_port=${port}
            break
        fi
    done
fi

if [ ! -n "${pr_port}" ]; then
    echo "Not Find vaild port"
    exit 1
fi

echo "Start Docker as $(date '+%Y-%m-%d %H:%M:%S')"

cp nginx.conf ${dir}/nginx.conf
sed -i "s/listen 80;/listen ${pr_port};/g" ${dir}/nginx.conf
sed -i "s/# server_name docs.mogdb.io;/server_name docs.mogdb.io;/g" ${dir}/nginx.conf

docker run -d \
    -v ${dir}/nginx.conf:/etc/nginx/nginx.conf \
    -v ${publicDir}:/usr/share/nginx/html \
    -p ${pr_port}:${pr_port} \
    --name ${conName} \
    nginx


echo "${pr_port}" > ${pr_port_file}
echo "Build End as $(date '+%Y-%m-%d %H:%M:%S')"
